<template>
  <div class="order-page">
    <van-cell-group inset>
      <van-field
        v-model="custName"
        label="客户名称"
        readonly
      />

      <van-field
        v-model="billDate"
        label="单据日期"
        readonly
        @click="showDatePicker = false"
      />
      <van-button
        block
        type="primary"
        @click="handleShowProductPicker"
      >
        选择检测项目
      </van-button>
    </van-cell-group>

    <van-cell-group inset v-if="selectedProducts.length" style="max-height: 60vh; overflow-y: auto; ">
      <van-cell
        v-for="(item, index) in selectedProducts"
        :key="item.pk_material"
        :title="`${item.matname}    ${item.vcheckmethod} ${item.spec}`"
        :value="`单价: ¥${item.price}`"
      >
        <template #extra>
          <div style="display: flex; flex-direction: column; gap: 4px">
            <!-- <div class="original-price">¥{{ item.price }}</div> -->
            <div style="display: flex; flex-direction: column; gap: 8px; padding-left: 12px">
              <div class="divider-line"></div>
              <span class="subtotal-display">¥{{ (item.price * item.num).toFixed(2) }}</span>
              <van-stepper
                v-model="item.num"
                min="1"
                @change="calculateAmount(index)"
              />
            </div>
          </div>
        </template>
      </van-cell>
      <van-cell title="合计金额" :value="`¥${totalAmount}`" />
    </van-cell-group>

    <van-button
      block
      type="primary"
      class="submit-btn"
      @click="handleSubmit"
    >
      提交订单
    </van-button>

    <van-popup v-model:show="showDatePicker" position="bottom">
      <van-date-picker
        v-model="currentDate"
        @confirm="confirmDate"
        @cancel="showDatePicker = false"
      />
    </van-popup>
    <van-popup v-model:show="showProductPopup" position="bottom" style="height: 60%">
      <div style="display: flex; flex-direction: column; height: 100%;">
        <van-field
          v-model="searchKeyword"
          placeholder="输入检测项目"
          clearable
          required
          label="检测项目"
          @change="handleSearch"
        />

        <div style="flex: 1; overflow-y: auto; padding: 0 16px; height: calc(100% - 120px); min-height: 200px;">
          <van-checkbox-group v-model="selectedProductIds">
            <van-cell-group>
              <van-cell
                v-for="product in productList"
                :key="product.pk_material"
                :title="`${product.matname}    ${product.vcheckmethod} ${product.spec}`"
                :label="'单价: ¥' + product.price"
                style="align-items: flex-start;"
              >
                <template #right-icon>
                  <van-checkbox :name="product.pk_material" />
                </template>
              </van-cell>
            </van-cell-group>
          </van-checkbox-group>
        </div>

        <div style="padding: 16px; margin-top: auto; position: sticky; bottom: 0; background: white; z-index: 1;">
          <van-button block type="primary" @click="confirmProductSelection">确认选择</van-button>
          <van-button 
            v-if="hasMore" 
            block 
            plain 
            type="primary" 
            style="margin-top:8px"
            @click="loadMore"
          >
            加载更多
          </van-button>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import dayjs from 'dayjs'
import { showToast  } from 'vant'
import service from '@/api'
import { useRoute, useRouter } from 'vue-router'


const custName = ref('')
const billDate = ref(dayjs().format('YYYY-MM-DD'))
const showDatePicker = ref(false)
const currentDate = ref([
  dayjs().format('YYYY'),
  dayjs().format('MM'),
  dayjs().format('DD')
])
const route = useRoute()

const selectedProducts = ref([])
const selectedProductIds = ref([])
const totalAmount = ref(0)
const showProductPopup = ref(false)
const productList = ref([])
const searchKeyword = ref('')
const pageNum = ref(1)
const pageSize = 10
// 默认不显示
const hasMore = ref(false)

// const handleSearch = async () => {
//   pageNum.value = 1
//   await loadProducts()
// }

const handleSearch = () => {
    pageNum.value = 1
    loadProducts();
}

const loadMore = async () => {
  pageNum.value++
  await loadProducts()
}

const loadProducts = async () => {
  try {
    const res = await service.getProductList({itype:"filterMaterialMhQuery",info:{
        productCode: searchKeyword.value,
      }
    })
    
    if (res.status=='success') {
      productList.value = res.data.elements;
    } else {
      alert(res.message);
    }
  } catch (error) {
    showToast('加载失败')
  }
}

// 用户openId
let openId = route.query.openId ||'';
if(!openId){
    let src = window.location.href;
    let index= src.indexOf("?");
    if(index >0){
      let dataStr= src.substring(src.indexOf("?")+ 1);
      let param = dataStr.split("=");
      openId = param[1];
    }
  }

const confirmProductSelection = () => {
  selectedProducts.value = productList.value.concat(selectedProducts.value)
    .filter(p => selectedProductIds.value.includes(p.pk_material))
    .map(p => ({ ...p, num: 1 }))
  calculateTotal()
  showProductPopup.value = false
}

const calculateTotal = () => {
  totalAmount.value = selectedProducts.value.reduce((sum, item) => sum + (Number(item.price) * item.num), 0).toFixed(2)
}

const calculateAmount = () => {
  calculateTotal()
}
const target = route.query.target || '/#/order'
const handleSubmit = async () => {
  // TODO: 调用订单提交接口
  service.submitOrder(
    { itype:"saleorder_save",//订单保存
    info:
    {
      //custName: custName.value,
    billDate: billDate.value,
    products: selectedProducts.value,
    openId : openId!=null?openId:localStorage.getItem('userInfo').openId
  }}).then((res) => {
    //debugger
    if (res.status == 'success') {
      //showToast('订单提交成功')
      alert(res.message);
     // window.location.reload;
      window.location.href = target+'?openId='+openId
    } else {
      //alert(res.message);
     showToast(res.message);
    }
  })
}

onMounted(() => {
  const userInfo = JSON.parse(localStorage.getItem('userInfo'))
  if (userInfo) {
    custName.value = userInfo.custname
  }
})

const handleShowProductPicker = async () => {
  showProductPopup.value = true
  // await loadProducts()
}
</script>

<style scoped>
.submit-btn {
  margin: 20px auto;
  width: 90%;
}

.product-item {
  padding: 12px;
  margin: 8px 0;
  background: #f7f8fa;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}

.subtotal-display {
  color: #07c160;
  font-weight: bold;
  font-size: 14px;
}

.original-price {
  color: #969799;
  font-size: 12px;
}

.divider-line {
  border-top: 1px solid #ebedf0;
  margin: 4px 0;
}
</style>
